package com.flyme.module.base.provider.controller;

import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysComplanRemoteService;
import com.flyme.module.base.client.dto.SysComplanDto;
import com.flyme.module.base.client.entity.SysComplan;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.file.client.entity.SysCourse;
import com.flyme.module.file.provider.service.SysCataLogService;
import com.flyme.module.file.provider.service.SysCourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 企业学习计划管理
 *
 * @author zyf
 */
@Api(tags = "企业学习计划管理")
@RestController
public class SysCompanyPlanController extends BaseController<SysComplanService, SysComplan> implements SysComplanRemoteService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysUsersturecordService usersturecordService;
    @Autowired
    private SysCataLogService cataLogService;
    @Autowired
    private SysCourseService courseService;
    @Autowired
    private SysPlanrecordService planrecordService;

    /**
     * 企业学习计划列表
     *
     * @return
     */
    @ApiOperation(value = "企业学习计划列表", notes = "企业学习计划列表")
    @Override
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysComplan complan) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.addSql("id,planName,starTime,endTime,createTime,courseIds,userIds,deptIds,CONCAT(courseTimes,'分钟') courseTimes");
        cq.addSql("CASE WHEN NOW()<starTime THEN '未开始' WHEN NOW()>endTime THEN '已结束' ELSE '进行中' END planStatus");
        cq.like("planName", complan.getPlanName());
        cq.eq("companyId", userAuth.getCompanyId());
        cq.ge("starTime", complan.getStartDate());
        cq.le("endTime", complan.getEndDate());
        if (OpenHelper.hasRole("hr")) {
            //hr账户只查看自己创建的计划
            cq.eq("hrId", userAuth.getUserId());
        }
        PqGrid pqGrid = bizService.pageList(cq);
        //计算完成度
        List<EntityMap> list = pqGrid.getRows();
        for (EntityMap map : list) {
            Long complanId = map.get("id");
            map.put("degree", 0);
            if (ObjectUtils.isNotEmpty(map.get("courseIds"))) {
                String[] ids = map.get("courseIds").toString().split(",");
                Integer userN = 1;
                if (ObjectUtils.isNotEmpty(map.get("userIds"))) {
                    String[] users = map.get("userIds").toString().split(",");
                    userN = users.length;
                }
                if(ObjectUtils.isNotEmpty(map.get("deptIds"))){
                    String[] deptIds = map.get("deptIds").toString().split(",");
                    List<String> userList = userService.selectByDept(deptIds);
                    userN = userList.size();
                }
                //计算该计划的总视频数量:计划的数量x人员数量
                Integer allNum = cataLogService.countByCourseIds(ids) * userN;
                //计算该计划的已看完的总视频数量
                Integer userNum = usersturecordService.countByPlanNum(complanId);
                BigDecimal degree = new BigDecimal(userNum.toString()).divide(new BigDecimal(allNum.toString()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                map.put("degree", degree);
            }
        }
        return ResultBody.success(pqGrid);
    }


    /**
     * 企业部门列表
     */
    @ApiOperation(value = "企业部门列表", notes = "企业部门列表")
    public ResultBody getDepartmentList(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysComplanDto complanDto) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        SysUser comUser = userService.getById(userAuth.getUserId());
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("*");
        cq.eq("parentId", 0);
        cq.eq("companyId", comUser.getCompanyId());
        cq.like("deptName", complanDto.getDeptName());
        PqGrid pqGrid = deptService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 添加学习计划
     */
    @ApiOperation(value = "添加学习计划", notes = "添加学习计划")
    public ResultBody add(@ModelAttribute(value = "course") SysComplanDto complanDto) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        complanDto.setCompanyId(userAuth.getCompanyId());
        complanDto.setHrId(userAuth.getUserId());
        SysComplan companyPlan = bizService.findByName(complanDto.getPlanName(), complanDto.getCompanyId());
        if (ObjectUtils.isNotEmpty(companyPlan)) {
            return ResultBody.failed("已经存在改学习计划");
        }
        if (ObjectUtils.isEmpty(complanDto.getUserIds())) {
            complanDto.setUserIds(null);
        }
        if (ObjectUtils.isEmpty(complanDto.getCourseIds())) {
            complanDto.setCourseIds(null);
        }
        if (ObjectUtils.isEmpty(complanDto.getDeptIds())) {
            complanDto.setDeptIds(null);
        }
        boolean tag = bizService.saveOrUpdate(complanDto);
        if(tag){
            planrecordService.addPlanRecord(complanDto.getUserIds(), complanDto.getId(), complanDto.getDeptIds());
        }
        return ResultBody.success(tag);
    }

    /**
     * 修改学习计划
     */
    @ApiOperation(value = "修改学习计划", notes = "修改学习计划")
    public ResultBody edit(@ModelAttribute(value = "course") SysComplanDto complanDto) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        complanDto.setHrId(userAuth.getUserId());
        complanDto.setCompanyId(userAuth.getCompanyId());
        if (ObjectUtils.isEmpty(complanDto.getUserIds())) {
            complanDto.setUserIds("");
        }
        if (ObjectUtils.isEmpty(complanDto.getCourseIds())) {
            complanDto.setCourseIds("");
        }
        if (ObjectUtils.isEmpty(complanDto.getDeptIds())) {
            complanDto.setDeptIds("");
        }
        boolean tag = bizService.saveOrUpdate(complanDto);
        if(tag){
            planrecordService.addPlanRecord(complanDto.getUserIds(), complanDto.getId(), complanDto.getDeptIds());
        }
        return ResultBody.success(tag);
    }

    /**
     * 删除计划
     */
    @ApiOperation(value = "删除学习计划", notes = "删除学习计划")
    public ResultBody removePlan(@PathVariable Long complanId) {
        boolean tag = bizService.removeById(complanId);
        return ResultBody.success(tag);
    }


    /**
     * 修改查询学习计划信息
     */
    @ApiOperation(value = "学习计划", notes = "学习计划")
    public ResultBody complanInfo(@PathVariable Long complanId) {
        SysComplan complan = bizService.getOne(q().select("planName,id,starTime,endTime,courseIds,userIds,deptIds,courseTimes").eq("id", complanId));
        EntityMap map = new EntityMap();
        map.put("planName", complan.getPlanName());
        map.put("id", complan.getId());
        map.put("starTime", complan.getStarTime());
        map.put("endTime", complan.getEndTime());
        map.put("courseIds", new ArrayList<>());
        map.put("courseTimes", complan.getCourseTimes());
        if (ObjectUtils.isNotEmpty(complan.getCourseIds())) {
            String[] cIds = complan.getCourseIds().split(",");
            List<Map<String, String>> list = new ArrayList<>();
            for (String id : cIds) {
                Long userId = Long.valueOf(id);
                Map<String, String> data = new HashMap<>();
                SysCourse course = courseService.getById(userId);
                if (ObjectUtils.isNotEmpty(course)) {
                    data.put("id", course.getId().toString());
                    data.put("courseTitle", course.getCourseTitle());
                }
                list.add(data);
            }
            map.put("courseIds", list);
        }
        map.put("userIds", new ArrayList<>());
        if (ObjectUtils.isNotEmpty(complan.getUserIds())) {
            String[] uIds = complan.getUserIds().split(",");
            List<Map<String, String>> list = new ArrayList<>();
            for (String id : uIds) {
                Long userId = Long.valueOf(id);
                Map<String, String> data = new HashMap<>();
                SysUser user = userService.getById(userId);
                if (ObjectUtils.isNotEmpty(user)) {
                    data.put("id", user.getId().toString());
                    data.put("userName", user.getUserName());
                }
                list.add(data);
            }
            map.put("userIds", list);
        }
        map.put("deptIds", new ArrayList<>());
        map.put("deptName", new ArrayList<>());
        if (ObjectUtils.isNotEmpty(complan.getDeptIds())) {
            String[] deptIds = complan.getDeptIds().split(",");
            map.put("deptIds", deptIds);
            List<String> names = new ArrayList<>();
            for (String id : deptIds) {
                Long dId = Long.valueOf(id);
                String deptName = deptService.getById(dId).getDeptName();
                names.add(deptName);
            }
            map.put("deptName", names);
        }
        return ResultBody.success(map);
    }

    /**
     * 查询学习计划中的员工
     */
    @ApiOperation(value = "计划中员工", notes = "计划中员工")
    public ResultBody getStaffData(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysComplanDto complanDto) {
        SysComplan complan = bizService.getById(complanDto.getPlanId());
        if (ObjectUtils.isEmpty(complan.getUserIds()) && ObjectUtils.isEmpty(complan.getDeptIds())) {
            return ResultBody.failed("推送员工为空");
        }
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName", "nickName", "avatar", "mobile", "email", "age", "sex", "userType", "dept.deptName departmentTitle", "positionName", "status", "u.createTime");
        cq.like("u.jobNo", complanDto.getJobNo());
        cq.like("u.userName", complanDto.getUserName());
        if (ObjectUtils.isNotEmpty(complanDto.getDeptIds())) {
            cq.in("u.deptId", complanDto.getDeptIds().split(","));
        }
        if (ObjectUtils.isNotEmpty(complan.getUserIds())) {
            cq.in("u.id", complan.getUserIds().split(","));
        }
        cq.eq("u.userType", "UT_STUDENT");
        cq.ge("u.hiredate", complanDto.getStartDate());
        cq.le("u.hiredate", complanDto.getEndDate());
        cq.createAlias("dept", "dept");
        PqGrid pqGrid = userService.pageList(cq);
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();
        //计算学习进度
        //计算所有课程总视频数量
        Integer allNum = cataLogService.countByCourseIds(complan.getCourseIds().split(","));
        for (EntityMap em : list) {
            //计算用户该计划一共看了的视频数量
            Integer userNum = usersturecordService.countByPlan(em.get("id"), complanDto.getPlanId());
            BigDecimal degree = new BigDecimal(userNum).divide(new BigDecimal(allNum), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
            if (degree.compareTo(new BigDecimal(100)) == 1) {
                degree = new BigDecimal("100");
            }
            em.put("degree", degree);
        }
        pqGrid.setRows(list);
        return ResultBody.success(pqGrid);
    }


    /**
     * 查询学习计划课程
     */
    @ApiOperation(value = "学习计划的课程", notes = "学习计划的课程")
    public ResultBody getCourseData(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysComplanDto complanDto) {
        SysComplan complan = bizService.getById(complanDto.getPlanId());
        if (ObjectUtils.isEmpty(complan.getCourseIds())) {//课程为空
            return ResultBody.failed("该计划未添加课程");
        }
        String[] courseId = complan.getCourseIds().split(",");
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("c.courseTitle,c.courseImage,lecturer.lecturerName,(select count(id) from sys_catalog ca where ca.courseId=c.id and parentId!=0) courseCount");
        cq.in("c.id", courseId);
        cq.like("c.courseTitle", complanDto.getUserName());
        cq.createAlias("lecturer", "lecturer");
        PqGrid pqGrid = courseService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 查询学习计划推送给的部门
     */
    @ApiOperation(value = "学习计划的部门", notes = "学习计划的部门")
    public ResultBody getDeptData(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysComplanDto complanDto) {
        SysComplan complan = bizService.getById(complanDto.getPlanId());
        if (ObjectUtils.isEmpty(complan.getDeptIds())) {//课程为空
            return ResultBody.failed("该计划未推送部门");
        }
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("deptName, id");
        cq.in("id", complan.getDeptIds().split(","));
        cq.like("deptName", complanDto.getUserName());
        PqGrid pqGrid = deptService.pageList(cq);
        //计算部门完成度
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();
        //计算所有课程总视频数量
        Integer allNum = cataLogService.countByCourseIds(complan.getCourseIds().split(","));
        for (EntityMap map : list) {
            //计算用户该计划一共看了的视频数量
            String userNum = usersturecordService.countByPlan(complanDto.getPlanId(), map.get("id"), complan.getCompanyId());
            BigDecimal degree = new BigDecimal(userNum).divide(new BigDecimal(allNum.toString()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
            map.put("degree", degree);
        }
        pqGrid.setRows(list);
        return ResultBody.success(pqGrid);
    }

}
